import scipy.optimize as opt


class NewtonMethod:
    # 定义方程
    # def equation(self,x, a0, a1, a2, a3, y):
    #     return (-a0 + 3 * a1 - 3 * a2 + a3) * x ** 3 + (-a0 - 6 * a1 + 3 * a2) * x ** 2 + (
    #                 -3 * a0 + 3 * a1) * x + a0 - y

    def equation(self, t, a0, a1, a2, x):
        return (1 - t) ** 2 * a0 + 2 * t * (1 - t) * a1 + a2 * t ** 2 - x

    # 已知的 y 值和参数
    y = 500
    p0 = 0
    p1 = 166.666
    p2 = 333.333

    # 使用牛顿法求解方程
    x0 = 0.0  # 初始估计值
    solution = opt.newton(equation, x0, args=(p0, p1, p2, y))


# 打印解
print(f"x = {solution}")

a0 = 500
a1 = 333.333
a2 = 166.666
a3 = 0

# 使用牛顿法求解方程
x0 = 0.0  # 初始估计值

res = (1 - solution) ** 3 * a0 + 3 * (1 - solution) ** 2 * solution * a1 + 3 * (
        1 - solution) * solution ** 2 * a2 + solution ** 3 * a3
print(res)
